<template>
  <div>
    <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
  </div>
</template>
<script>
import UploadExcel from '@/components/UploadExcel'
import { formatExcelDate } from '@/utils/index.js'
import { importEmployee } from '@/api/employees'
export default {
  name: 'HrsassImport',
  components: {
    UploadExcel
  },
  data() {
    return {}
  },

  mounted() {},

  methods: {
    async importEmployee(data) {
      await importEmployee(data)
      this.$router.back()
      this.$message.success('导入成功')
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      const newData = this.transExcel(results, header)
      console.log(newData)
      this.importEmployee(newData)
    },
    transExcel(results, header) {
      const mapInfo = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName',
        聘用形式: 'formOfEmployment'
      }
      return results.map((item) => {
        const zhKeys = Object.keys(item)
        const obj = {}
        zhKeys.forEach((key) => {
          if (
            mapInfo[key] === 'timeOfEntry' ||
            mapInfo[key] === 'correctionTime'
          ) {
            obj[mapInfo[key]] = new Date(formatExcelDate(item[key]))
          } else {
            obj[mapInfo[key]] = item[key]
          }
        })
        return obj
      })
    }
  }
}
</script>
